﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using WeBlog;
using WeBlog.DataContext;
using WeBlog.Models;
using WeBlog.Repositories;
using WeBlog.Resources;
using WeBlog.Services;
using Page = WeBlog.Models.Page;

public static class HTMLHelpers {
	public static string CurrentVersion(this HtmlHelper helper) {
		try {
			Version version = Assembly.GetExecutingAssembly().GetName().Version;
			return version.Major + "." + version.Minor + "." + version.Build + "." + version.Revision;
		}
		catch (Exception) {
			return "?.?.?";
		}
	}

	public static MvcHtmlString GravatarImage(this HtmlHelper helper, string email, string title)
	{
		var html =  String.Format("<img src='http://www.gravatar.com/avatar/{0}.jpg?s=48' alt='{1}' class='gravatar' height='48' width='48' />",
			Utils.GetMD5Hash(email),
			title);
		return MvcHtmlString.Create(html);
	}

	public static MvcHtmlString AddThisLink(this HtmlHelper helper, Post post, string className )    
	{
		var writer = new HtmlTextWriter(new StringWriter());
		
		var builder = new UriBuilder(helper.GetBaseUri());         
		builder.Path = "/Posts/" + post.Slug;
		writer.AddAttribute( HtmlTextWriterAttribute.Href, builder.Uri.AbsoluteUri );
		writer.AddAttribute( "addthis:title", post.Title );
		writer.AddAttribute( "addthis:url", builder.Uri.AbsoluteUri );
		writer.AddAttribute( HtmlTextWriterAttribute.Class, className );
		writer.RenderBeginTag(HtmlTextWriterTag.A);
		writer.RenderEndTag();

		return MvcHtmlString.Create( writer.InnerWriter.ToString() );
	}

	public static MvcHtmlString Ratings(this HtmlHelper helper, Post post)
	{	    
		bool needLoginToRate = !(SiteManager.CurrentConfiguration.AllowAnonymousRatings
			|| HttpContext.Current.Request.IsAuthenticated);

		float average = 0;

		if( post.PostRatings.Any() ) 
			average = post.PostRatings.Average(x => x.Rating);

		StringBuilder sb = new StringBuilder();

		string tooltip = needLoginToRate ? Strings.Post_StarRatingLoginToVote : Strings.Post_StarRatingClickToVote;

		sb.AppendFormat("<span class='postRating' rating='{0}' post='{1}' title='{2}'>", 
						average, 
						post.PostId,
						tooltip);

		string formatStr = "<span class='rating stars {2}star-{0}' value='{1}'></span>";
		string actIt = needLoginToRate ? "" : "active ";
		
		for (double i = .5; i <= 5.0; i = i + .5) {
			if (i <= (double)average) {
				sb.AppendFormat(formatStr, (i * 2) % 2 == 1 ? "left_on" : "right_on", i, actIt);
			}
			else {
				sb.AppendFormat(formatStr, (i * 2) % 2 == 1 ? "left_off" : "right_off", i, actIt);
			}
		}

		if( post.PostRatings.Any() )
			sb.AppendFormat("&nbsp;<span>" + Strings.Post_StarRatingText + "</span>", average, post.PostRatings.Count);
		else
			sb.AppendFormat("&nbsp;<span>{0}</span>", Strings.Post_NotRatedYet );
		sb.Append("</span>");
		return new MvcHtmlString(sb.ToString());
	}

	public static MvcHtmlString PageDropDown(this HtmlHelper helper)
	{
	    var isAdmin = System.Threading.Thread.CurrentPrincipal.IsAdmin();

	    List<Page> pages;
        using( var context = new WeBlogContext())
        {
            var pageRepository = new PageRepository(context);
            pages = pageRepository.FindPublished();
        }

		if (!pages.Any() && !isAdmin)
			return MvcHtmlString.Empty;

		var sb = new StringBuilder();
		sb.Append("<ul id='jsddm'>");
		sb.AppendFormat("<li><a href='#'>{0}</a>", Strings.Pages);
		sb.Append("<ul>");

		foreach (var p in pages)
			sb.AppendFormat("<li><a href='/Pages/{0}'>{1}</a></li>", p.Slug, p.Title);

		if (isAdmin)
		{
			sb.AppendFormat("<li><a href='/Page/Create'><strong>{0}</strong></a></li>", Strings.Page_Create);
		}
		sb.Append("</ul></li></ul>");
		return MvcHtmlString.Create(sb.ToString());                
	}
}